<template>
  <el-dropdown size="mini" type="default" trigger="hover" @command="onCommand">
    <el-button size="mini" type="primary" plain @click="onClick">{{btn.label}}<i v-if="items.length" class="el-icon-arrow-down el-icon--right"></i></el-button>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item v-for="(item, index) in items" :key="index" :command="item.value || index">{{item.label}}</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'OsTableDropdown',
  props: {
    list: Array
  },
  computed: {
    ...mapState({
      resources: state => state.resources
    }),
    mList () {
      return this.list.filter(item => {
        if (item.show === false) return false
        if (item.permission === undefined || item.permission === '') return true
        if (typeof item.permission === 'string' && this.resources.includes(item.permission)) {
          return true
        } else if (Array.isArray(item.permission)) {
          return item.permission.some(item => this.resources.includes(item))
        } else if (typeof item.permission === 'boolean') {
          return item.permission
        }
      })
    },
    btn () {
      return this.mList[0]
    },
    items () {
      return this.mList.slice(1)
    }
  },
  data () {
    return {
    }
  },
  methods: {
    onClick () {
      this.btn.cb && this.btn.cb()
      this.$emit('select', this.btn.value || 0)
    },
    onCommand (value) {
      const item = this.items.find((v, index) => v.value === value || index === value)
      if (item) {
        item.cb && item.cb()
        this.$emit('select', item.value || value + 1)
      }
    }
  }
}
</script>
